<template>
  <div >
<!--    第一项 搜索框和重置按钮-->
    <div class="card">
      <el-input v-model="data.searchName" placeholder="请输入员工姓名" style="width: 200px;margin-right: 5px;" suffix-icon="Search"/>
      <el-button type="primary" @click="loadData()">搜索</el-button>
      <el-button type="warning" @click="reset()">重置</el-button>
    </div>

<!--    第二项 常用操作 批量删除 添加员工-->
    <div class="card">
      <el-button type="primary" @click="switchAddDialog">新建员工</el-button>
      <el-button type="danger" @click="deleteBatchMessageBox">批量删除</el-button>
    </div>

<!--    第三项 员工数据表格-->
    <div class="card">
     <el-table @selectionChange="handleSelectionChange" :data = "data.tableData" height="400" style="width: 100%;border: #7a7575 solid 1px">
       <el-table-column type="selection" width="55" />
       <el-table-column prop="id" label="编号" />
       <el-table-column prop="username" label="账号" />
       <el-table-column prop="" label="头像" >
         <template #default="scope">
           <img v-if="scope.row.avatar" :src="scope.row.avatar" alt="" style="width: 50px;height: 50px;border-radius: 50%;">
         </template>

       </el-table-column>

       <el-table-column prop="role" label="角色" />
       <el-table-column prop="name" label="姓名" />
       <el-table-column prop="gender" label="性别" />
       <el-table-column prop="title" label="职位" />
       <el-table-column prop="birthday" label="出生日期"/>
       <el-table-column fixed="right" label="操作" width="120">
         <template #default="scope">
           <el-button  type="primary"  @click="editRow(scope.row)" circle>
             <el-icon><Edit /></el-icon>
           </el-button>
           <el-button  type="danger" @click="deleteMessageBox(scope.row)" circle>
             <el-icon><Delete /></el-icon>
           </el-button>
         </template>
       </el-table-column>

     </el-table>
    </div>

<!--    第四项 分页组件-->
    <div class="card">
      <el-pagination

          v-model:current-page="data.currentPage"
          v-model:page-size="data.pageSize"
          @current-change="loadData"
          @size-change="loadData"
          :page-sizes="[10, 20, 50, 100]"

          layout="total, sizes, prev, pager, next, jumper"
          v-model:total="data.total"

      />
    </div>

    <el-dialog
        v-model="data.AddDialogVisible"
        title="新建员工"
        width="500"
        destroy-on-close
    >
      <el-form ref="formRef" :rules="data.rules" :model="data.employee" style="padding-right: 40px;padding-top: 20px" >
      <el-form-item label="账号" prop="username">
      <el-input :disabled="data.employee.id == 0" v-model="data.employee.username" autocomplete="off" placeholder="请输入账号"></el-input>
      </el-form-item>
      <el-form-item label="头像" prop="avatar">
        <el-upload
            :action="$baseUrl + '/files/upload'"
            list-type="picture"
            :on-success="handleAvatarSuccess"

        >
          <el-button type="primary ">上传头像</el-button>
        </el-upload>

      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="data.employee.password" autocomplete="off"  placeholder="请输入密码"></el-input>
      </el-form-item>
      <el-form-item label="角色">
        <el-input v-model="data.employee.role" autocomplete="off"  placeholder="请输入角色"></el-input>
      </el-form-item>
      <el-form-item label="名称" prop="name">
        <el-input v-model="data.employee.name" autocomplete="off"  placeholder="请输入名称"></el-input>
      </el-form-item>
      <el-form-item label="性别" >
        <el-radio-group v-model="data.employee.gender" id="gender-radio-group">
          <el-radio value="男" size="large" border>男</el-radio>
          <el-radio value="女" size="large" border>女</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="职称">
        <el-input v-model="data.employee.title" autocomplete="off"  placeholder="请输入职称"></el-input>
      </el-form-item>

      <el-form-item label="出生日期">

        <el-date-picker
            v-model="data.employee.birthday"
            type="date"
            placeholder="选择出生日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
        />
      </el-form-item>
</el-form>

        <template #footer>
          <div class="dialog-footer">
            <el-button @click="switchAddDialog">取消</el-button>
            <el-button type="primary" @click="save()">
              确定
            </el-button>
          </div>
        </template>


    </el-dialog>
  </div>
</template>
<script setup>

import {reactive,ref} from "vue";
import request from "@/utils/request.js";

import {ElMessage,ElMessageBox} from "element-plus";

const res = ref();
const data =  reactive({
  AddDialogVisible:false,
  tableData: [
  ],
  currentPage:1,
  pageSize:5,
  searchName:'',
  employee:{
    id:0,
    username:'',
    password:'',
    role:'',
    name:'',
    gender:'',
    title:'',
    birthday:'',
    avatar:''
  },
  ids:[],
  rules:{
    username:[
      {required:true,message:'请输入账号',trigger:'blur'},
      {min:3,max:10,message:'长度在3到10个字符',trigger:'blur'}
    ],
    password:[
      {required:true,message:'请输入密码',trigger:'blur'},
      {min:3,max:10,message:'长度在3到10个字符',trigger:'blur'}
    ],
    role:[
      {required:true,message:'请输入角色',trigger:'blur'},
    ],
    name:[
      {required:true,message:'请输入名称',trigger:'blur'}
    ]
  }

})
const formRef = ref();
const loadData = () => {


  const loadAll = () =>{

        request.get('employee/selectPage', {
          params: {
            pageNum: data.currentPage,
            pageSize: data.pageSize,
          }
        }).then(res=> {
          data.tableData = res.data.list;
          data.total = res.data.total;

          console.log(res.data.list)
        })
      }
      const loadByName = () =>{
        request.post('employee/findByName',{
            name:data.searchName,
        },{  params: {
                pageNum: data.currentPage,
                pageSize: data.pageSize,
              }}).then(res=>{
          data.tableData = res.data.list;
          data.total = res.data.total;
          console.log(res.data.list)
        })
        }
  data.searchName ? loadByName() :loadAll()
}
loadData();
const reset = () =>{
  data.searchName = '';
  loadData();
}
const switchAddDialog = () =>{
  data.AddDialogVisible = data.AddDialogVisible ? false : true;
}
const editRow = (row) =>{
  data.employee = row;
  switchAddDialog();
  //深拷贝,解决就算取消修改，数据还是被修改了的问题
  data.employee = JSON.parse(JSON.stringify(row));

}
const save = () =>{
  formRef.value.validate((valid) => {
    if (valid) {
      console.log('校验通过');
      data.employee.id != 0 ? update() : add();
    } else {
      console.log('校验不通过');
      return false;
    }
  });

}
const update = () =>{
  request.put('employee/modify',data.employee).then(res=>{
    console.log(res);
    if(res.code === '200'){
      ElMessage.success('添加成功');
      loadData();
      switchAddDialog();
    }else {
      ElMessage.error(res.code + '/n' + res.msg);
    }
  })
}
const add = () =>{
  request.post('employee/add',data.employee).then(res=>{
    console.log(res);
    if(res.code === '200'){
      ElMessage.success('添加成功');
      loadData();
      switchAddDialog();
    }else {
      ElMessage.error(res.code + '/n' + res.msg);
    }
  })
}
const deleteOne = (row) =>{
  request.delete(`employee/deleteById/${row.id}`).then(res=>{
    if(res.code === '200'){
      ElMessage.success('删除成功');
      loadData();
    }else {
      ElMessage.error(res.code + '/n' + res.msg);
    }
  })
}
const handleSelectionChange = (rows) =>{
  data.ids = rows.map(row => row.id);
  console.log(data.ids);
}
const deleteBatch = () =>{
  request.delete(`employee/deleteBatch`,{data:data.ids}).then(res=>{
    if(res.code === '200'){
      ElMessage.success('批量删除成功');
      loadData();
    }else {
      ElMessage.error(res.code + '/n' + res.msg);
    }

  })
}
const deleteMessageBox = (row) =>{
  ElMessageBox.confirm('此操作将永久删除该信息, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'danger',
  }).then(() => {
    deleteOne(row);
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '已取消删除',
    });
  });
}
const deleteBatchMessageBox = () =>{
  if(data.ids.length === 0){
    ElMessage.error('请选择要删除的数据');
    return;
  }
  ElMessageBox.confirm('此操作将永久删除该信息, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'danger',
  }).then(() => {
    deleteBatch();
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '已取消删除',
    });
  });
}
const handleAvatarSuccess = (res) => {
  console.log(res.data)
  data.employee.avatar = res.data.url

}
</script>
